package com.common.service.impl;

import com.common.entity.SupperEntity;
import com.common.entity.TreeEntity;
import com.common.model.TreeModel;
import com.common.mysql.Where;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Description:
 * @Date: 2025/6/24 10:06
 */
public class TreeSimpleServiceImpl<I, M extends TreeModel<I>, E extends TreeEntity<I>> extends SimpleServiceImpl<I, M, E> {

    public List<M> buildTree(List<M> modelList) {
        //获取所有parentId为空的集合，所有顶级节点
        List<M> topList = modelList.stream().filter(m -> ObjectUtils.isEmpty(m.getParentId()))
                .collect(Collectors.toList());
        if (CollectionUtils.isEmpty(topList)) {
            return Collections.emptyList();
        }
        Map<I, List<M>> childrenMap = modelList.stream()
                .filter(m -> !ObjectUtils.isEmpty(m.getParentId()))
                .collect(Collectors.groupingBy(TreeModel::getParentId));
        build(topList, childrenMap);
        return topList;
    }

    public void build(List<M> currentModelList, Map<I, List<M>> childrenMap) {
        if (CollectionUtils.isEmpty(currentModelList)) {
            return;
        }
        for (M currentModel : currentModelList) {
            I id = currentModel.getId();
            if (childrenMap.containsKey(id)) {
                List<M> children = childrenMap.get(id);
                build(children, childrenMap);
                currentModel.setChildren(children);
            }
        }
    }
}
